<?php
require_once "UserClass.php";

/**
 * PayerClass 
 *
 * This class is designed to work with payers.
 *
 * @author Victor Magarlamov <victor.magarlamov@gmail.com>
 * @version 1.0
 * @package presstrack
 */
class PayerClass extends UserClass
{
	public $_explicitType = "presstrack.PayerClass";    
	
	public $mMediumName;
	
	function __construct() 
	{		
    }
	
	/**
	 * ReadFromDb
	 *	 
     * set user's data from database
	 *
	 * @param	int	$iduser	user ID
     */
	function ReadFromDb($iduser)
	{
		set_time_limit(0);
		$sql = "SELECT name, medium, section FROM press_track_new.user "
			 . "WHERE iduser = $iduser LIMIT 1";
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		$res 				= mysql_fetch_object($query);
		$this->iUserId		= $iduser;
		$this->iMediumId	= $res->medium;
		$this->mName		= $res->name;
		$this->iSection		= $res->section;
		
		$sql = "SELECT name FROM press_track_new.user "
			 . "WHERE iduser = $this->iMediumId LIMIT 1";
		$query = mysql_query($sql);
		$res 				= mysql_fetch_object($query);
		$this->mMediumName	= $res->name;
		
		$sql = "SELECT * FROM press_track_new.contacts " 
			 . "WHERE user = $iduser ORDER BY type";
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}		
		
		while ($contact = mysql_fetch_object($query))
		{		
			$this->arContact[] = $contact;
		}
		
		$current_year = date("Y");
		
		$this->GetStatisticForYear($current_year);
	}
	
	/**
	 * GetStatisticForCustomerForYear
	 *	 
     * collecting statistical info about payer - 
	 * sum of debt
	 *
	 * @param	int	$year	filter by year
     */
	function GetStatisticForYear($year)
	{
		set_time_limit(0);
		
		// debt
		$sql = "SELECT SUM(debt) AS debt FROM press_track_new.order "
			 . "WHERE press_track_new.order.customer = $this->iUserId "
			 . "AND press_track_new.order.creation LIKE '%$year'";
		$query = mysql_query($sql);
		$res = mysql_fetch_object($query);		
		$this->obStatistic->dDebt = round($res->debt, 2);
	}
	
	/**
	 * GetPayers
	 *	 
     * return payers
	 *
	 * @return	array		$result		array of payers
     */
	static function GetPayers() 
	{
		$sql = sprintf("SELECT iduser, name FROM press_track_new.user "
			 . "WHERE medium > -1 ORDER BY name");
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		set_time_limit(0);
		while ($payer = mysql_fetch_object($query)) 
		{
			$user = new PayerClass();
			$user->ReadFromDb($payer->iduser);
			$result[] = $user;
		}
		return $result;
	}	
}
?>